package com.malex.mxtracker;

import com.malex.mxtracker.bean.Bank;
import com.malex.mxtracker.bean.Currency;
import com.malex.mxtracker.bean.Operation;
import com.malex.mxtracker.bean.Project;
import com.malex.mxtracker.component.HomePage;
import com.malex.mxtracker.store.EM;
import org.apache.wicket.protocol.http.HttpSessionStore;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.session.ISessionStore;

import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MxTracker extends WebApplication {
    /**
     * Валюта от которой расчитанны теекущие курсы
     */
    private static String defaultCurrencyCode;
    /**
     * Текущие курсы валют в системе
     */
    private static Map<String, Currency> currencies;
    /**
     * Доступные пакеты денег
     */
    private static Map<Long, Bank> banks;
    /**
     * Список проектов
     */
    private static Map<Long, Project> projects;


    public MxTracker() {
        setCurrencies(new HashMap<String, Currency>());
        setBanks(new HashMap<Long, Bank>());
        setProjects(new HashMap<Long, Project>());
    }

    @Override
    protected void init() {
        super.init();
        getResourceSettings().setResourcePollFrequency(null);
    }

    @Override
    protected ISessionStore newSessionStore() {
        return new HttpSessionStore(this);
    }

    /**
     * @see org.apache.wicket.Application#getHomePage()
     */
    public Class<HomePage> getHomePage() {
        return HomePage.class;
    }

    public static void readCurrencies() {
        EntityManager em = EM.get().createEntityManager();
        try {
            Map<String, Currency> currencyMap = new HashMap<String, Currency>();
            String query = String.format("select from %s", Currency.class.getName());
            for (Object o : em.createQuery(query).getResultList()) {
                Currency c = (Currency) o;
                currencyMap.put(c.getCharCode(), c);
            }
            MxTracker.updateCurrencies(currencyMap);
        } finally {
            em.close();
        }
    }

    public static void readBanks() {
        EntityManager em = EM.get().createEntityManager();
        try {
            MxTracker.getBanks().clear();
            String query = String.format("select from %s", Bank.class.getName());
            for (Object o : em.createQuery(query).getResultList()) {
                Bank bank = (Bank) o;
                MxTracker.getBanks().put(bank.getId(), bank);
            }
        } finally {
            em.close();
        }
    }

    public static void readProjects() {
        EntityManager em = EM.get().createEntityManager();
        try {
            MxTracker.getProjects().clear();
            String query = String.format("select from %s", Project.class.getName());
            for (Object o : em.createQuery(query).getResultList()) {
                Project project = (Project) o;
                MxTracker.getProjects().put(project.getId(), project);
            }
        } finally {
            em.close();
        }
    }

    public static List<Operation> readOperations(String prjId) {
        List<Operation> result = new ArrayList<Operation>();
        EntityManager em = EM.get().createEntityManager();
        try {
            String query = String.format("select from %s where project=%s",
                    Operation.class.getName(), prjId);
            for (Object o : em.createQuery(query).getResultList()) {
                result.add((Operation) o);
            }
        } finally {
            em.close();
        }
        return result;
    }

    public static Map<String, Currency> getCurrencies() {
        return currencies;
    }

    public static void setCurrencies(final Map<String, Currency> currencies) {
        MxTracker.currencies = currencies;
    }

    public static void updateCurrencies(final Map<String, Currency> currencies) {
        getCurrencies().clear();
        getCurrencies().putAll(currencies);
        /**
         * Определяем валюту по умолчанию
         */
        defaultCurrencyCode = null;
        for (Currency c : getCurrencies().values()) {
            if (c.getDef() != null && c.getDef()) {
                defaultCurrencyCode = c.getCharCode();
            }
        }
        if (defaultCurrencyCode == null) {
            defaultCurrencyCode = "blr";
        }
    }

    public static Map<Long, Bank> getBanks() {
        return banks;
    }

    public static Map<Long, Project> getProjects() {
        return projects;
    }

    public static void setProjects(final Map<Long, Project> projects) {
        MxTracker.projects = projects;
    }

    public static void setBanks(final Map<Long, Bank> banks) {
        MxTracker.banks = banks;
    }

    public static void updateData() {
        readCurrencies();
        readBanks();
        readProjects();
    }
}
